package com.wzh.utils;

import com.wzh.bean.book.BookInfo;
import com.wzh.constant.CollectConstant;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// /\* [1-9 ]\d+ \*/
public class BookCollectUtil {
    private static int timeout = 5000;
    public static String srcStr;
    public static BookCollectUtil.ContentJsoup contentJsoup;

    public static String getWebContentByUrl(String desturl, String charSet) {
        StringBuilder result = new StringBuilder("");
        try {
            if (false) {
                URL url = new URL(desturl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(timeout);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Host", "www.555zw.com");
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
                conn.connect();

                int code = conn.getResponseCode();
                if (code == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is, charSet));
                    String tempStr;
                    while ((tempStr = br.readLine()) != null) {
                        result.append(tempStr).append("\n");
                    }
                    is.close();
                    br.close();
                }
            } else {
                Connection connection = Jsoup.connect(desturl);
                connection.timeout(7000);
                Document doc1 = connection.get();
                result.setLength(0);
                result.append(doc1.toString());
            }

            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ContentJsoup getWebContentDocumentByUrl(String desturl, String charSet) {
        ContentJsoup contentJsoup = new ContentJsoup();
        try {

            Connection connection = Jsoup.connect(desturl);
            connection.timeout(7000);
            Document doc1 = connection.get();
            contentJsoup.setContent(doc1.toString());
            contentJsoup.setDocument(doc1);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return contentJsoup;
    }

    public static String getContentByReg(String reg, String srcStr) {
        if ((reg == null) || ("".equals(reg))) {
            return null;
        }

        if ((srcStr == null) || ("".equals(srcStr))) {
            return null;
        }

        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(srcStr);

        if (matcher.find()) {
            String str = matcher.group(1);
            return str;
        }
        return null;
    }

    //目前仅调试使用到了，调试的时候 用了一个方法解析，这里有点写的麻烦了
    public static String getContentByReg_jsoup(String reg, String srcStr, String key) {
        if ((reg == null) || ("".equals(reg))) {
            return null;
        }
        if ((srcStr == null) || ("".equals(srcStr))) {
            return null;
        }
        if ("content".equals(key)) {
            String _re = HtmlJsoupUtil.getMaxContentEl(srcStr).html();
            if (_re != null && _re.length() > 50) {
                return _re;
            }
        }
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(srcStr);
        if (matcher.find()) {
            String str = matcher.group(1);
            return str;
        }
        return null;
    }


    public static String getContentByReg(String reg, String srcStr, String[] oldStrList, String[] newStrList) {
        if ((reg == null) || ("".equals(reg))) {
            return null;
        }

        if ((srcStr == null) || ("".equals(srcStr))) {
            return null;
        }

        srcStr = replaceStr(srcStr, oldStrList, newStrList);

        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(srcStr);

        if (matcher.find()) {
            String str = matcher.group(1);
            return str;
        }
        return null;
    }

    public static List<String> getUrls(String reg, String srcStr, String domain) {
        if ((srcStr == null) || ("".equals(srcStr))) {
            return null;
        }

        if ((reg == null) || ("".equals(reg))) {
            return null;
        }

        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(srcStr);

        List matchList = new ArrayList();
        while (matcher.find()) {
            String url = matcher.group(1);
            if ((url != null) && (!url.startsWith("http")) &&
                    (domain != null)) {
                url = "http://" + domain + url;
            }

            matchList.add(url);
        }

        return matchList;
    }

    public static Map<String, String> getChapterTitleAndUrl(String reg, String[] oldStrList, String[] newStrList, String domain, String charset) {
        if ((srcStr == null) || ("".equals(srcStr))) {
            return null;
        }
        if ((reg == null) || ("".equals(reg))) {
            return null;
        }
        Map matchMap = new LinkedHashMap();
        srcStr = replaceStr(srcStr, oldStrList, newStrList);
        Logger.getAnonymousLogger().info("==================getChapterTitleAndUrl-begin");
        matchMap = HtmlJsoupUtil.getBookCapterLink(contentJsoup, domain, charset);
        Logger.getAnonymousLogger().info("==================getChapterTitleAndUrl-matchMap.size():"+matchMap.size());
        if(matchMap.size()>20){
            return matchMap;
        }
        Logger.getAnonymousLogger().info("==================getChapterTitleAndUrl:《20普通方案" );

        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(srcStr);


        while (matcher.find()) {
            String url = matcher.group(1);
            if ((url != null) && (!url.startsWith("http")) &&
                    (domain != null)) {
                url = "http://" + domain + url;
            }

            String regStr = matcher.group(2);

            matchMap.put(url, regStr);
        }

        return matchMap;
    }

    public static Map<String, String> getRegedMapByUrl(String srcStr, Map<String, String> regs, String[] oldStrList, String[] newStrList) {
        if ((srcStr == null) || ("".equals(srcStr))) {
            return null;
        }
        if ((regs == null) || (regs.size() == 0)) {
            return null;
        }

        Map map = new HashMap();

        String bookStr = replaceStr(srcStr, oldStrList, newStrList);

        for (Map.Entry entry : regs.entrySet()) {
            String regedStr = getContentByReg((String) entry.getValue(), bookStr);
            Logger.getAnonymousLogger().info((String) entry.getValue() + ":" + (String) entry.getKey() + ":" + regedStr);
            map.put((String) entry.getKey(), regedStr);
        }
        return map;
    }

    public static String replaceStr(String srcStr, String[] oldList, String[] newList) {
        if ((srcStr == null) || ("".equals(srcStr))) {
            return srcStr;
        }
        int i = 0;
        String returnStr = "";

        if (oldList == null) {
            return srcStr;
        }

        if (newList == null) {
            for (String oldStr : oldList) {
                returnStr = srcStr.replace(oldStr, "");
                srcStr = returnStr;
            }

            return returnStr;
        }

        if (oldList.length <= newList.length) {
            for (String oldStr : oldList) {
                returnStr = srcStr.replace(oldStr, newList[i]);
                srcStr = returnStr;
                i++;
            }
        } else {
            for (String newStr : newList) {
                returnStr = srcStr.replace(oldList[i], newStr);
                srcStr = returnStr;
                i++;
            }
            for (; i < oldList.length; i++) {
                returnStr = srcStr.replace(oldList[i], "");
                srcStr = returnStr;
            }
        }
        return returnStr;
    }

    public static BookInfo getBookInfos(String contenturl, String charset, String domain, Map<String, String> regs, String[] oldStrList, String[] newStrList) {
        BookInfo bookInfo = new BookInfo();
        Logger.getAnonymousLogger().info("开始获取url内容：" + contenturl);
        BookCollectUtil.ContentJsoup contentJsoup1 = getWebContentDocumentByUrl(contenturl, charset);
        srcStr =contentJsoup1.getContent();
        contentJsoup = contentJsoup1;

        if ((srcStr == null) || ("".equals(srcStr))) {
            return null;
        }
        Logger.getAnonymousLogger().info("开始解析bookinfo对象,url:" + contenturl);
        Map regedMap = getRegedMapByUrl(srcStr, regs,
                oldStrList, newStrList);

        if ((regedMap == null) || (regedMap.size() == 0)) {
            return null;
        }

        String imageurl = (String) regedMap.get(CollectConstant.IMAGEURL);
        if ((imageurl != null) && (!"".equals(imageurl))) {
            if (!imageurl.startsWith("http")) {
                imageurl = "http://" + domain + imageurl;
            }
            bookInfo.setImageurl(imageurl);
        }

        bookInfo.setAuthor((String) regedMap.get(CollectConstant.AUTHOR));
        String booktype = (String) regedMap.get(CollectConstant.BOOKTYPE);
        if (booktype != null && booktype.contains("玄幻"))
            bookInfo.setBooktype(Integer.valueOf(1));
        else if (booktype != null && booktype.contains("重生"))
            bookInfo.setBooktype(Integer.valueOf(2));
        else if (booktype != null && booktype.contains("科幻"))
            bookInfo.setBooktype(Integer.valueOf(3));
        else if (booktype != null && booktype.contains("网游"))
            bookInfo.setBooktype(Integer.valueOf(4));
        else if (booktype != null && booktype.contains("历史"))
            bookInfo.setBooktype(Integer.valueOf(5));
        else if (booktype != null && booktype.contains("都市"))
            bookInfo.setBooktype(Integer.valueOf(6));
        else if (booktype != null && booktype.contains("修真"))
            bookInfo.setBooktype(Integer.valueOf(7));
        else if (booktype != null && booktype.contains("武侠"))
            bookInfo.setBooktype(Integer.valueOf(8));
        else {
            bookInfo.setBooktype(Integer.valueOf(9));
        }

        bookInfo.setIntro((String) regedMap.get(CollectConstant.INTRO));
        String title = (String) regedMap.get(CollectConstant.TITLE);
        if (title != null) {
            bookInfo.setTitle(title.trim());
        }

        bookInfo.setUpdatetime(CommonUtil.stringToDate((String) regedMap.get(CollectConstant.UPDATETIME)));

        String state = (String) regedMap.get(CollectConstant.BOOKSTATE);
        if ("已完结".equals(state)) {
            bookInfo.setIsfinish(true);
        }
        bookInfo.setResourceUrl(contenturl);

        return bookInfo;
    }
    static class ContentJsoup{
        public Document document = new Document("");
        public String content="";

        public Document getDocument() {
            return document;
        }

        public void setDocument(Document document) {
            this.document = document;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}


/* Location:           C:\work\apache-tomcat-7.0.55\webapps\ROOT\WEB-INF\classes\
 * Qualified Name:     com.wzh.utils.BookCollectUtil
 * JD-Core Version:    0.6.1
 */